/**
 * 
 */
package com.liferayinaction.portlet;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;



/**
 * @author kyamav
 *
 */
public class HelloYouPortlet extends GenericPortlet {
	private static Log _log = LogFactoryUtil.getLog(HelloYouPortlet.class);
	private String editJSP;
	private String viewJSP;
	
	public void init() throws PortletException {
	editJSP = getInitParameter("edit-jsp");
	viewJSP = getInitParameter("view-jsp");
	}
	
	public void doView(RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {
		PortletPreferences prefs = renderRequest.getPreferences();
		String username = (String) prefs.getValue("name", "no");
		if (username.equalsIgnoreCase("no")) {
			username = "";
		}
		renderRequest.setAttribute("userName", username);
		include(viewJSP, renderRequest, renderResponse);
	}
	
	public void doEdit(RenderRequest renderRequest,
			RenderResponse renderResponse)
			throws IOException, PortletException {
			renderResponse.setContentType("text/html");
			PortletURL addName = renderResponse.createActionURL();
			addName.setParameter("addName", "addName");
			renderRequest.setAttribute("addNameUrl", addName.toString());
			include(editJSP, renderRequest, renderResponse);
			}
	
	public void processAction(
			ActionRequest actionRequest,
			ActionResponse actionResponse)
			throws IOException, PortletException {
			String addName = actionRequest.getParameter("addName");
			if (addName != null) {
			PortletPreferences prefs =
			actionRequest.getPreferences();
			prefs.setValue(
			"name", actionRequest.getParameter("username"));
			prefs.store();
			actionResponse.setPortletMode(PortletMode.VIEW);
			}
			}
	
	protected void include(String path, RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {
		PortletRequestDispatcher portletRequestDispatcher = getPortletContext()
				.getRequestDispatcher(path);
		if (portletRequestDispatcher == null) {
			_log.error(path + " is not a valid include");
		} else {
			portletRequestDispatcher.include(renderRequest, renderResponse);
		}
	}

}
